<?php

namespace App\Http\Controllers\Api\User;

use App\Http\Controllers\Api\System\JSSDKConfigController;
use App\Http\Controllers\ApiController;

use App\Http\Controllers\PCHController;
use App\Models\Balance;
use App\Models\Comment;
use App\Models\CopartnerApply;
use App\Models\distribution;
use App\Models\System;
use App\Models\User;
use App\Models\Vip;
use DB;
use Illuminate\Http\Request;
use App\Http\Models\User\UserBaseModel;
use Illuminate\Support\Facades\Redis;
use phpDocumentor\Reflection\Types\Self_;


class UCenterController extends ApiController
{
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * @return $this
     * @throws \ErrorException
     * 获取意见反馈分类列表
     */
    public function getFeedBackCate()
    {
        $data = UserBaseModel::getFeedBackCate();
        return self::response($data,200);
    }

    /**
     * @param Request $request
     * @return $this
     * @throws \ErrorException
     * 提交意见反馈
     */
    public function submitFeedBack(Request $request)
    {
        $data = $request->all();
        if (empty($data['uid'])){
            return self::response(null,'-2','用户id不能为空');
        }

        if (empty($data['content'])){
            return self::response(null,-4,'请填写反馈内容');
        }

        if (empty($data['phone'])){
            return self::response(null,-4,'请填写手机号');
        }

        $tmp['uid']     = $data['uid'];
        $tmp['content'] = $data['content'];
        $flag =  UserBaseModel::addSuggestion($tmp);

        if ($flag!==false){
           return self::response(null,'200','操作成功');
        }else
            return self::response(null,-5,'操作失败');
    }


    /**
     * @param Request $request
     * @return $this
     * @throws \ErrorException
     * 我的用户中心
     */
    public function myUCenter(Request $request)
    {
        $data = $request->all();

        if (empty($data['uid']))
        {
            return self::response(null,'-1','用户不能为空');
        }
        #redis 缓存取数据
        $key        = PCHController::getUserInfoKeyByUID($data['uid']);
        $myUserInfo = Redis::HGETALL($key);
        #如果不存在 则读取Mysql
        if (empty($myUserInfo)){
            $myUserInfo = UserBaseModel::getUserInfo($data['uid']);
        }

        if (empty($myUserInfo)){
            return self::response(null,-2,'用户信息不存在');
        }
        return self::response($myUserInfo,200);
    }



    public function follow(Request $request)
    {
        $data = $request->all();
        if (empty($data['uid'])||empty($data['to_uid'])){
            return self::response('','-1','数据异常');
        }
        $res = UserBaseModel::addFollow($data['uid'],$data['to_uid']);
        if ($res['status']==false){
            return self::response(null,'-1','网络错误，操作失败');
        }elseif($res['status'] == 3&&isset($res['msg'])){
            return self::response(null,'-2',$res['msg']);
        }else{
            return self::response(null,200,'关注成功');
        }
    }


    /**
     * @param Request $request
     * @return $this
     * @throws \ErrorException
     */
    public function addAddress(Request $request)
    {
        $input = $request->all();
        if (empty($input['uid'])){
            return self::response(null,'-1','用户id为空');
        }

        if (empty($input['phone'])){
            return self::response(null,'-1','请填写手机号');
        }

        if (empty($input['name'])){
            return self::response(null,'-1','请填写姓名');
        }
        if (empty($input['province'])){
            return self::response(null,'-1','请选择省');
        }

        if (empty($input['city'])){
            return self::response(null,'-1','请选择市');
        }

        if (empty($input['dist'])){
            return self::response(null,'-1','请选择区');
        }

        if (empty($input['content'])){
            return self::response(null,'-1','请填写详细地址');
        }
        $res= UserBaseModel::addAddress($input);
        return self::response('',$res['ret'],$res['msg']);
    }


    /**
     * @param Request $request
     * @return $this
     * @throws \ErrorException
     */
    public function editAddress(Request $request)
    {
        $input = $request->all();
        if (empty($input['address_id'])){
            return self::response(null,'-1','地址id为空');
        }

        $res = UserBaseModel::editAddress($input);
        return self::response('',$res['ret'],$res['msg']);
    }


    /**
     * @param Request $request
     * @return $this
     * @throws \ErrorException
     */
    public function addressList(Request $request)
    {
        $input = $request->all();
        if (empty($input['uid'])){
            return self::response(null,'-1','用户id为空');
        }
        $data = UserBaseModel::getAddressById($input['uid']);
        if (empty($data)){
            return self::response(null,200);
        }else{
            $user = UserBaseModel::getUser($input['uid']);
            foreach ($data as &$val){
            	if (is_object ($val)){
					$val = get_object_vars($val);
				}

				$val['province'] 	= explode  ('/',$val['province']);
				$val['city'] 			= explode  ('/',$val['city']);
				$val['dist'] 			= explode  ('/',$val['dist']);


                if ($val['id'] == $user['defaultAddress']){
                    $val['is_default'] = 1;
                }else{
                    $val['is_default'] = 0;
                }
            };
            if (empty($user['defaultAddress'])){

                $data[0]['is_default'] = 1;
            }
            return self::response($data,200);
        }
    }


    /**
     * @param Request $request
     * @return $this
     * @throws \ErrorException
     */
    public function delAddress(Request $request)
    {
        $input = $request->all();
        if (empty($input['address_id'])){
            return self::response(null,'-1','地址id不能为空');
        }

        if (empty($input['uid'])){
            return self::response(null,'-1','uid不能为空');
        }

        $input['address_id'] = json_decode($input['address_id']);

        if (!is_array($input['address_id'])||empty($input['address_id'])){
            return self::response(null,'-1','地址id必须为数组');
        }
        $res = UserBaseModel::delAddress($input['address_id'],$input['uid']);
        if ($res>0){
            return self::response(null,200,'删除成功');
        }else{
            return self::response(null,-2,'删除失败');
        }
    }


    /**
     * @param Request $request
     * @return $this
     * @throws \ErrorException
     */
    public function setDefaultAddress(Request $request)
    {
        $input = $request->all();
        if (empty($input['address_id'])){
            return self::response(null,'-1','地址id不能为空');
        }
        if (empty($input['uid'])){
            return self::response(null,'-2','uid不能为空');
        }
        if (!is_numeric($input['address_id'])){
            return self::response(null,'-1','地址id错误');
        }
		$address = DB::table ('address')
									->where('uid',$input['uid'])
									->where('id',$input['address_id'])
									->first();

        if (empty($address)){
        	return self::response (null,'-3','地址错误');
		}

        $res = UserBaseModel::setDefaultAddress($input['uid'],$input['address_id']);
        if ($res>0){
            return self::response(null,'200','设置成功');
        }else{
            return self::response(null,-3,'设置失败');
        }
    }


	public function getAddressByAddressId(Request $request){
		$input = $request->all();
		if (empty($input['address_id'])){
			return self::response(null,'-1','地址id不能为空');
		}

		$data = UserBaseModel::getAddressByAddressId ($input['address_id']);
		if (empty($data)){
			return  self::response (null,-2,'地址信息不存在');
		}

		$data['province'] 	= explode  ('/',$data['province']);
		$data['city'] 				= explode  ('/',$data['city']);
		$data['dist'] 				= explode  ('/',$data['dist']);

		return self::response ($data,200);
	}





    public function version()
    {
        $data = UserBaseModel::getVersion();
        if (empty($data)){
            return self::response(null,-1,'暂无信息');
        }else{
            return self::response($data);
        }
    }


    public function getBalanceRecord(Request $request)
    {
        $input = $request->all();
        if (empty($input['uid'])){
            return self::response(null,-1,'uid is null');
        }

        if (empty($input['amount_type'])){
            return self::response(null,-2,'amount_type is null');
        }

        if (!isset($input['nowPage'])){
            return self::response(null,-3,'当前页不能为空');
        }

        $skip = $input['nowPage']  *10;
        $data = UserBalanceModel::getBalanceRecord($input['uid'],$input['amount_type'],$skip);
        if (!empty($data)){
            foreach ($data as &$val){
                $val['create_at'] = date('Y-m-d H:i:s',$val['create_at']);
            }
        }
        return self::response($data,200);
    }


    public function bindInviteCode(Request $request)
    {
        $input = $request->all();
        if (empty($input['uid'])){
            return self::response(null,-1,'uid is null');
        }

        if (empty($input['Invite_code'])){
            return self::response(null,-2,'Invite_code is null');
        }

        #根据邀请码 获取 邀请码用户 信息
        $Invite   = UserBaseModel::getUserByInviteCode($input['Invite_code']);
        if (empty($Invite)||empty($Invite->id)||($Invite->id == $input['uid'])){
            return self::response(null,-3,'邀请码错误');
        }

        $flag     = UserBaseModel::bindInviteCode($input['uid'],$Invite->id);
        if ($flag != false){
            return self::response(null,200);
        }else{
            return self::response(null,200,'绑定失败，稍后再试');
        }
    }


    public function ApplyForMailingList(Request $request)
    {
        $input = $request->all();
        if (empty($input['uid'])){
            return self::response(null,-1,'uid is null');
        }

        if (empty($input['apply_ids'])){
            return self::response(null,-2,'apply_ids is null');
        }

        $apply_ids = json_decode($input['apply_ids']);

        if (!is_array($apply_ids)){
            return self::response(null,-3,'doll_id error');
        }

        $data['list']           = UserDollsModel::getDollInfo($input['uid'],$apply_ids);
        $count                  = count($data['list']);
        $postage                = 0;
        $payment_status         = 0;

        if (empty($data['list'])){
            return self::response(null,'-4','数据错误');
        }

        if ($count<2&&$data[0]['num']<2){
            $postage            = 10;
            $payment_status     = 1;
        }

       $order['postage']               = $postage;
       $order['payment_status']        = $payment_status;
       $order['apply_ids']             = $apply_ids;
       $data['order']                  = $order;

       return self::response($data);

    }


    public function ApplyForMailing(Request $request)
    {
        $input = $request->all();
        if (empty($input['order'])){
            return self::response(null,-1,'order is null');
        }

        if (empty($input['uid'])){
            return self::response(null,-2,'uid is null');
        }

        $order = json_decode($input['order'],true);
        if (empty($order['apply_ids'])||!is_array($order['apply_ids'])){
            return self::response(null,-3,'apply_ids is null or not array');
        }

        if (!isset($order['postage'])){
            return self::response(null,-4,'postage is null');
        }

        if (!isset($order['payment_status'])){
            return self::response(null,-5,'payment_status is null');
        }

        if (empty($input['address_id'])){
            return self::response(null,-6,'address_id is null');
        }

        $data   = UserDollsModel::getDollData($input['uid'],$order['apply_ids']);
        $sn                                 = Controller::get_order_sn();
        $sn                                .= '_V2';

        #获取地址信息
        $address = UserBaseModel::getAddressByAddressId($input['address_id']);

        if (empty($address)){
            return self::response(null,-7,'地址为空');
        }

        $address = get_object_vars($address);

        //        #写入记录
        $flag    = ApplyMailModel::insertMailRecord($data,$order['apply_ids'],$order['payment_status'],$order['postage'],$address,$sn,$input['uid']);

        if ($flag>0){
            if ($order['payment_status']==1){
                return self::response(['order_sn'=>$sn],200,'少于2件，需要支付邮费10元');
            }else{
                return self::response(['order_sn'=>$sn],200);
            }
        }else{
            return self::response(null,-7,'操作失败，稍后再试');
        }
    }

    /**
     * 付邮费
     */
    public function editMailingStat(Request $request)
    {
        if (!$request->input('order_sn'))
        {
            return self::response([],40001,'缺少参数order_sn');
        }
        $apply = ApplyMailingModel::where('order_sn','=',$request->input('order_sn'))->select()->first();
        if (empty($apply))
        {
            return self::response([],40002,'未查询到订单');
        }
        if ($apply->payment_status != 1)
        {
            return self::response([],40003,'订单状态不需要支付');
        }

        $pay     = new AliPayController();
        return $pay->pay($request->input('order_sn'), $apply->postage,"娃娃提货付邮费-{$apply->postage}CNY");

    }


    /**
     * 根据id改密码
     * @param Request $request
     * @return mixed
     * @throws \ErrorException
     */
    public function modifyPwdById(Request $request)
    {
        $input      = $request->all();
        if (empty($input['uid'])){
            return self::response(null,'-1','empty uid');
        }

        if (empty($input['user_password'])){
            return self::response(null,'-1','empty user_password');
        }

       $data =  UserBaseModel::updateUser($input['uid'],['user_password'=>$input['user_password']]);
        return self::response($data['data'],$data['ret'],$data['msg']);
    }


    #修改用户信息
    public function modifyUser(Request $request)
    {
        $userInfo   =  $request->all();
        $res        = UserBaseModel::checkUserInfo($userInfo);
        return self::response($res['data'],$res['ret'],$res['msg']);
    }


    public function bindVipCard(Request $request)
    {
        $input = $request->all();

        if (empty($input['uid'])){
            return self::response(null,-1,'uid null');
        }

        if (empty($input['vip_card_sn'])){
            return self::response(null,'-2','请输入会员卡卡号');
        }

        if (empty($input['user_name'])){
            return self::response(null,-3,'请输入绑卡用户名');
        }

        if (empty($input['money'])){
            return self::response(null,-3,'请输入会员卡金额');
        }

        $partner = CopartnerApply::getPartnerInfoByUserId($input['uid']);
        if (empty($partner)){
            return self::response(null,-4,'您不是合伙人，不能进行此操作！');
        }

        $vip_card = Vip::isBind($input['vip_card_sn']);
        if (empty($vip_card)){
            return self::response(null,-5,'会员卡不存在或是已被使用');
        }

        if ($partner['id'] == $input['uid']){
            return self::response(null,-6,'不能为自己绑定会员卡');
        }
        $data      = [
            'uid'                   => $input['uid'],
            'vip_card_sn'           => $input['vip_card_sn'],
            'shop_name'             => $partner['shop_name'],
            'shop_id'               => $partner['id'],
            'partner_uid'           => $input['uid'],
            'vip_card_status'       => 1,
            'money'                 => $input['money'],
        ];
        $flag                       = Vip::bindVipCard($input['vip_card_sn'],$data);
        if ($flag){
            return self::response(null,200);
        }else{
            return self::response(null,-7,'操作失败');
        }
    }

    /**我的推荐列表
     * @param Request $request
     */
    public function myInvitation(Request $request,User $userModel,distribution $distrModel)
    {
        if(empty($request->input('user_id'))){
            return self::response(null,self::ERROR_CODE,'用户id不能为空');
        }
        $uid = $request->input('user_id');
        $direct_list = $distrModel-> api_my_benefit_total($uid,1);
        $direct_list['user_list'] = $userModel -> get_invite_user_list($uid,1);

        $indirect_list = $distrModel-> api_my_benefit_total($uid,[2,3,4]);
        $indirect_list['user_list'] = $userModel -> get_invite_user_list($uid,[2,3,4]);
        $list = [
            'direct_list'   => $direct_list,
            'indirect_list' => $indirect_list,
        ];
        return self::response($list,self::SUC_CODE,'获取数据成功');
    }

    #用于订单页默认地址的获取
    public function defaultAddress(Request $request)
    {
        if(empty($request->input('user_id'))){
            return self::response(null,self::ERROR_CODE,'用户id不能为空');
        }
        $uid        = $request -> input('user_id');
        $u_model    = User::query()->where('id','=',$uid)->first();
        $address    = [];

        #没有添加过默认的收获地址
        if(empty($u_model->defaultAddress) || !DB::table('address')->where('id','=',$u_model->defaultAddress)->first()){
            #则用排序在前的最新的收获地址
            $addressModel = DB::table('address')->where('uid','=',$uid)->orderBy('created_at')->first();
        }else{
            #有默认地址
            $addressModel = DB::table('address')->where('id','=',$u_model->defaultAddress)->first();
        }
        if(!empty($addressModel)){
//            dd(explode  ('/',$addressModel->city));
            $address = [
                'phone' => $addressModel->phone,
                'city'  => explode  ('/',$addressModel->city),
                'dist'  => explode  ('/',$addressModel->dist),
                'content'=>$addressModel->content,
                'name'  => $addressModel->name,
                'province' =>explode  ('/',$addressModel->province),
            ];
        }
        if(!empty($address)){
            return self::response($address,self::SUC_CODE,'获取数据成功');
        }
        return  self::response(null,self::ERROR_CODE,'未添加任何收货地址');
    }


    /**
     * 立即评价
     * @param Request $request
     * @return mixed
     * @throws \ErrorException
     */
    public function addComment(Request $request)
    {
        $input  = $request->all ();
        if (empty($input['uid'])){
            return self::response (null,-1,'登录信息错误');
        }
        if (empty($input['grade'])){
            return self::response (null,-1,'请选择登记');
        }

        if (empty($input['order_goods_id'])){
            return self::response (null,-1,'请选择购买记录');
        }

        $userBaseInfo           = User::getUserInfoById ($input['uid']);
        $input['avatar']        = $userBaseInfo['user_avatar']??'';

        $flag  = Comment::addComment ($input);
        if ($flag){
            return self::response (null,self::SUC_CODE);
        }else{
            return self::response (null,-2,'操作失败');
        }
    }

    public function myComment(Request $request)
    {
        $input = $request->all ();
        if (empty($input['uid'])){
            return self::response (null,-1,'登录信息错误');
        }
        $data = Comment::myComment ($input['uid']);
        return self::response($data,self::SUC_CODE);
    }



    public function myDistributionCenter(Request $request)
    {
        $input = $request->all ();
        if (empty($input['uid'])){
            return self::response (null,-1,'登录信息错误');
        }
        $data = distribution::myDistributionCenter ($input['uid']);
        return self::response ($data);
    }



    /**
     * 关于我们
     */
    public function aboutus(Request $request)
    {
        $aboutusMode = System::first();
        if(empty($aboutusMode)){
            $aboutusMode = [
                'name'  => '',
                'image' => '',
                'copyright' => '',
            ];
        }else{
            $aboutusMode -> toArray();
        }
        return self::response($aboutusMode,self::SUC_CODE,'获取成功');
    }


    public function getUploadToken()
    {
        $token = ApiController::uploadToken();
        return self::response(['UploadToken'=>$token,'uri'=>'http://pdgccdat2.bkt.clouddn.com/'],200);
    }


    public function getUserInfo(Request $request)
    {
       $input = $request->all();
       if (empty($input['uid'])){
           return self::response(null,'-1','登录信息错误');
       }
       $user                = UserBaseModel::getUser($input['uid']);
       $user['user_coin']   = sprintf('%.2f',$user['user_coin']);
       $user['withdraw']    = sprintf('%.2f',$user['user_coin']);
       unset($user['user_password']);
       return self::response(['user'=>$user],200);
    }


    public function getJsSdkConfig(Request $request)
    {
        $JsSdk = new JSSDKConfigController();
        $sign  = $JsSdk->getSignPackage($request->input('url'));
        return self::response($sign,200);
    }


    public function getBalance(Request $request)
    {
        $input = $request->all();
        $data = Balance::balance_list($input);
        return self::response($data,200);
    }








}
